angular.module('module.share', [
    'ngCookies',
])

    .config(['$stateProvider', function ($stateProvider) {
        $stateProvider
            .state('sharelist', {
                url: '/sharelist?access&userid&shopid',
                templateUrl: 'view/share/sharelist.html',
                controller: 'SharelistController'
            })
            .state('sharedetail', {
                url: '/sharedetail?access&userid&shopid&templateid',
                resolve:{
                    sharedetail:['$q','$state','$stateParams','TemplateService',function($q,$state,$stateParams ,TemplateService){
                        var deferred = $q.defer();
                        TemplateService.getuserallshare($stateParams.userid,$stateParams.shopid,$stateParams.templateid).$promise.then(function(data){
                            console.log(data)
                            $state.go('aftershare',{shopid:$stateParams.shopid,access:data[0].access,userid:$stateParams.userid,templateid:$stateParams.templateid});
                            deferred.reject(data);
                        },function(error){
                            deferred.resolve("null");
                        });
                        return deferred.promise;
                    }]
                },
                templateUrl: 'view/share/sharedetail.html',
                controller: 'SharedetailController'
            })
            .state('aftershare', {
                url: '/aftershare?access&userid&shopid&templateid',
                templateUrl: 'view/share/aftershare.html',
                controller: 'AftershareController'
            })
            .state('sharesuccess', {
                url: '/sharesuccess?access&userid&shopid&templateid&linkid',
                templateUrl: 'view/share/sharesuccess.html',
                controller: 'SharesuccessController'
            })
            .state('shareqrcode', {
                url: '/shareqrcode?access&shopid&templateid',
                templateUrl: 'view/share/shareqrcode.html',
                controller: 'ShareQrcodeController'
            })
    }])

    .controller('SharelistController', ['$scope', '$state', '$stateParams', 'TemplateService', function ($scope, $state, $stateParams, TemplateService) {
        //TemplateService.getuserbystatus(1).$promise.then(function (data) {
        //    console.log(data)
            TemplateService.gettemplate($stateParams.shopid,1).$promise.then(function (data) {
                $scope.allshare = data;
                console.log(data)
            })
        //})
        $scope.goshare = function (templateId) {
            $state.go('sharedetail', {
                templateid: templateId,
                access: $stateParams.access,
                shopid: $stateParams.shopid,
                userid: $stateParams.userid
            })
        };
        $scope.goaftershare = function () {
            $state.go('aftershare', {
                access: $stateParams.access,
                shopid: $stateParams.shopid,
                userid: $stateParams.userid
            })
        };

    }])
    .controller('SharedetailController', ['$scope', '$state', '$stateParams', 'TemplateService','EntranceService', function ($scope, $state, $stateParams, TemplateService,EntranceService) {
        //console.log(sharedetail);
        TemplateService.getrulebytemplateId($stateParams.templateid).$promise.then(function (data) {
            $scope.rule = data;
            console.log( $scope.rule)
            for(i=0;i< $scope.rule.length;i++){
                var threshold=$scope.rule[i].threshold;
                var amount=$scope.rule[i].amount;
                var money=Math.round(parseFloat(amount/100)*10000)/10000*100;
                console.log(money)
                var xsd= money.toString().split(".");
                console.log(xsd)
                if(xsd.length==1){
                    money=money.toString()+".00";
                    console.log(money)
                }
                if(xsd.length>1){
                    if(xsd[1].length<2){
                        money=money.toString()+"0";
                    }
                }
                $scope.rule[i].money=money+"%";

            }

        });
        //确定分享，主要生成该分享者access
        $scope.getshareaddr = function () {
            var entrance = {
                "parentAcode": "0",//目前分享系统与运营�?�撇�?关系，不做运营�??
                "uid": $stateParams.userid,
                "type": 2,//1代表运营者，2代表分享�?
                "param": ""
            };//初始化access内容
            EntranceService.add(entrance, function (data) {
                //添加成功
                var share = {
                    userId: $stateParams.userid,
                    shopId: $stateParams.shopid,
                    access: data.accesscode,
                    templateId: $stateParams.templateid,
                };//初始化生调用连接数据
                TemplateService.addlink(share,function(success){
                    //生成链接成功，准备跳转分润中心查看二维码，带入access
                    $state.go("aftershare",{access:data.accesscode,shopid:$stateParams.shopid,userid:$stateParams.userid,templateid:$stateParams.templateid});
                },function(error){
                    alert("系统出错，请联系管理员！")
                })
            })
        };
    }])
    .controller('AftershareController', ['$scope', '$state', '$stateParams','$filter','ShareSumService','ShareWithdService', function ($scope, $state, $stateParams,$filter, ShareSumService,ShareWithdService) {
        $scope.shopid = $stateParams.shopid;
        $scope.access = $stateParams.access;
        $scope.templateid = $stateParams.templateid;
        ShareSumService.getShareSum($stateParams.userid,$stateParams.shopid).$promise.then(function(sharesum){
            $scope.sharesum = sharesum;
            console.log($scope.sharesum);
        })
        ShareWithdService.getYue($stateParams.userid).$promise.then(function(userbalance){
            $scope.userbalance = userbalance;
            console.log(userbalance);
        })
        $scope.withdrawcash = function(){
            if($scope.sharesum){
                if($scope.sharesum.totalMoney){
                    if($scope.sharesum.totalMoney<10){
                        alert("佣金不足，提现至少10元");
                        return;
                    }
                    if( $scope.userbalance){
                        $(".specpanel-2yGNl").show();
                        $(".specpanel-2HhFg").show();
                        $(".specpanel-3_81U").show();
                        setTimeout(function () {
                            $(".specpanel-2HhFg").addClass("specpanel-EyF12");
                            $(".specpanel-3_81U").addClass("specpanel-3Y186");
                        }, 10);
                        //$("#withdrawcash").show();
                    }else{
                        alert("未开通余额,请到个人中心开通");
                        //window.location.href = wmappurl();
                    }
                }else{
                    alert("佣金不足");
                }
            }else{
                alert("佣金不足");
            }
        }
        //隐藏提现框
        $scope.closeInput = function(){
            $(".specpanel-2HhFg").removeClass("specpanel-EyF12");
            $(".specpanel-3_81U").removeClass("specpanel-3Y186");
            setTimeout(function () {
                $(".specpanel-2HhFg").hide();
                $(".specpanel-3_81U").hide();
                $(".specpanel-2yGNl").hide();
            }, 200);
        }
        $scope.judgebalance = function(num){
            if(num){
                if(num>$scope.sharesum.totalMoney){
                    iswithdrawcash = true;
                    alert("超出佣金");
                }else if(num<10){
                    iswithdrawcash = true;
                    alert("金额未满10元不能提现!");
                }else{
                    iswithdrawcash = false;
                    $scope.balance = parseFloat($filter('number')(num ,1));
                }
            }else{
                $scope.balance = null;
                iswithdrawcash = true;
                alert("输入有误!");
            }
        };
        //获取提现记录
        ShareWithdService.ShareWith($stateParams.userid,$stateParams.shopid).$promise.then(function(ShareWithList){
            $scope.ShareWithList = ShareWithList;
            console.log(ShareWithList);
        })
        var iswithdrawcash = false;
        $scope.sure_withdrawcash = function(){
            $scope.judgebalance($scope.balance);
            if($scope.balance<=0){
                return;
            }
            if(iswithdrawcash){
                return;
            }
            iswithdrawcash = true;
            var param = {
                "shopId": $stateParams.shopid,
                "userId": $stateParams.userid,
                "type": 1,//提现
                "amount": $scope.balance
            };
            //alert("开发中");
            ShareWithdService.insertWithd(param,function(data){
                $scope.sharesum.totalMoney -= $scope.balance
                var balance_param = {
                    "userid": $stateParams.userid,
                    "balance": $scope.balance+$scope.userbalance.balance
                };
                ShareWithdService.updateUserBalance(balance_param,function(response){
                    iswithdrawcash = false;
                    $scope.userbalance.balance += $scope.balance;
                    alert("提现成功！");
                    ShareWithdService.ShareWith($stateParams.userid,$stateParams.shopid).$promise.then(function(ShareWithList){
                        $scope.ShareWithList = ShareWithList;
                        console.log(ShareWithList);
                    })
                    $scope.closeInput();
                    console.log(response);
                },function(error){
                    iswithdrawcash = false;
                    alert("提现失败！");
                })
            },function(error){
                iswithdrawcash = false;
                alert("提现失败！");
                console.log(error);
            })
        }
    }])

    .controller('SharesuccessController', ['$scope', '$state', '$stateParams', 'TemplateService', function ($scope, $state, $stateParams, TemplateService) {
        var share = {
            userId: $stateParams.userid,
            shopId: $stateParams.shopid,
            access: $stateParams.access,
            templateId: $stateParams.templateid,
        };

        TemplateService.getuserallshare(share.userId, share.shopId, share.templateId).$promise.then(function (data) {
            $scope.allusershare = data;
            console.log($scope.allusershare)
            TemplateService.gettemplate(share.shopId).$promise.then(function (data) {
                console.log(data)
                $scope.allshare = data;
                for (var i = $scope.allshare.length - 1; i >= 0; i--) {
                    var templateId = $scope.allshare[i].templateId;
                    for (var j = $scope.allusershare.length - 1; j >= 0; j--) {
                        if ($scope.allusershare[j].templateId == templateId) {
                            $scope.allshare.splice(i, 1);
                        }
                    }

                }
            })
        });

        $scope.goshare = function (templateId) {
            $state.go('sharedetail', {
                templateid: templateId,
                access: $stateParams.access,
                shopid: $stateParams.shopid,
                userid: $stateParams.userid
            })
        };

    }])
    .controller('ShareQrcodeController', ['$scope','$stateParams','TemplateService', function ($scope,$stateParams,TemplateService) {
        $(document).ready(function(){
            var options={};
            options.url=mall_shareurl($stateParams.shopid,$stateParams.access); //二维码的链接
            options.dom="#code";//二维码生成的位置
            options.image="";//图片id
            options.render="image";//设置生成的二维码是canvas格式，也有image、div格式
            var size = $("#code").width();
            xyqrcode(options,size);
        });
        TemplateService.getsharebytemplateId($stateParams.templateid).$promise.then(function(template){
            $scope.template = template;
        })
}])